import React, { useEffect, useState, useRef } from 'react'
import ModelForm from '.././../../components/userlist/ModelForm'
import {
    getuserList, addUser,
    getRoleList, getRegion,
    deleteUser, changeState,
    updateUser
} from '../../../api/userlistApi'

import {
    ExclamationCircleOutlined
} from '@ant-design/icons';
import { Table, Button, Modal, Switch } from 'antd';
const { confirm } = Modal;

export default function UserList() {
    const [dataSource, setdatasource] = useState([])
    // 添加用户模态框的状态
    const [showModal, setshowModal] = useState(false)
    const [showUpdate, setshowUpdate] = useState(false)
    const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
    // 存储角色列表的状态
    const [roleList, setroleList] = useState([])
    const [updateItem, setupdateItem] = useState(null)
    // 存储地区列表的状态
    const [regionList, setregionList] = useState([])
    // 用户总条数
    const [total, setTotal] = useState(1)
    const myFrom = useRef(null)
    const myUpdataFrom = useRef(null)

    // 表头
    const columns = [
        {
            title: '区域',
            dataIndex: 'regionName',
            filters: [
                ...regionList.map(item => ({
                    text: item.value,
                    value: item.id
                })),
            ],
            onFilter: (value, item) => {
                return item.regionId === value
            },
            render: (regionName) => {
                return <b>{regionName}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render: (role) => {
                return role?.roleName
            }
        },
        {
            title: '用户名',
            dataIndex: 'userName',
            render: (username) => {
                return username
            }
        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render: (roleState, item) => {
                return <Switch checked={roleState}
                    disabled={item.defaultUser}
                    onChange={() => { changeRole(item) }}
                ></Switch>
            }
        },
        {
            title: '操作',
            render: (item) => {
                return (
                    <div>
                        <Button style={{ margin: '0 10px' }}
                            type="primary"
                            size='small'
                            danger
                            onClick={() => onDelete(item)}
                            disabled={item.defaultUser}
                        >删除</Button>
                        <Button
                            type="primary"
                            size='small'
                            disabled={item.defaultUser}
                            onClick={() => { switchMethod(item) }}
                        >编辑</Button>
                    </div>

                )
            }
        },
    ];

    // 副作用函数
    useEffect(() => {
        getList()
    }, [])
    useEffect(() => {
        // 获取角色列表
        getRoleList().then(res => {
            const list = res.roleList
            setroleList(list)
        })
    }, [])
    useEffect(() => {
        // 获取区域列表
        getRegion().then(res => {
            setregionList(res.regionList)
        })
    }, [])
    // 获取表格数据
    const getList = (page, limit) => {
        getuserList({
            page: page || 1,
            limit: limit || 10
        }).then((res) => {
            setTotal(res.userList.total)
            setdatasource(res.userList.records)
        })
    }

    // 删除按钮回调
    function onDelete(item) {
        confirm({
            title: '你确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                deleteUser(item.id).then((res) => {
                    getList()
                })
            },
            onCancel() {
            },
        });
    }
    // 编辑按钮配置
    const switchMethod = (item) => {
        setTimeout(() => {
            setshowUpdate(true)
            if (item.role.roleType === 1) {
                //禁用
                setisUpdateDisabled(true)
            } else {
                //取消禁用
                setisUpdateDisabled(false)
            }
            // 把本行数据传递给form表单
            myUpdataFrom.current.setFieldsValue({
                username: item.userName,
                password: null,
                regionId: item.regionId === 8 ? '' : item.regionId,
                roleId: item.role.roleType
            })
        }, 0)
        setupdateItem(item)
    }
    //添加用户模态框确定按钮回调
    const ModalConfirm = () => {
        myFrom.current.validateFields().then(value => {
            // 清空输入框，并隐藏模态框
            myFrom.current.resetFields();
            setshowModal(false)
            // post到后端，生成id，再设置重新请求一遍, 方便后面的删除和更新
            addUser({
                userName: value.username,
                roleId: value.roleId,
                regionId: value.regionId === '' ? 8 : value.regionId,
                passWord: value.password
            }).then((res) => {
                console.log(res);
                getList()
            })
        }).catch(err => {
            console.log(err)
        })
    }
    // 编辑模态框确定按钮
    const UpdateConfirm = () => {
        myUpdataFrom.current.validateFields().then(value => {
            setshowUpdate(false)
            // 重置form的可选，来防止可选状态不更新
            setisUpdateDisabled(!isUpdateDisabled)
            updateUser({
                id: updateItem.id,
                userName: value.username,
                passWord: value.password,
                roleId: value.roleId,
                regionId: value.regionId === '' ? 8 : value.regionId
            }).then((res) => {
                getList()
            })
        })
    }
    // 用户状态切换回调
    const changeRole = (item) => {
        item.roleState = !item.roleState
        setdatasource([...dataSource])
        changeState({
            userId: item.id,
            roleState: item.roleState
        }).then((res) => {
            console.log(res);
            getList()
        })
    }
    // 页码和条数改变的回调
    const handlePageChange = (page, pageSize) => {
        getList(page, pageSize)
    }
    return (
        <div>
            <Button
                style={{ margin: '0 0 10px 0' }}
                type="primary"
                onClick={() => {
                    setshowModal(true)
                }}
            >添加用户</Button>

            <Table dataSource={dataSource}
                columns={columns}
                pagination={{
                    total: total,
                    onChange: (page, pageSize) => handlePageChange(page, pageSize), //改变页码的函数
                    showSizeChanger: true,
                    pageSizeOptions: [10, 20, 30, 40, 50],
                    showQuickJumper: false,
                }}
                rowKey={item => item.id}
            />

            {/* 添加用户弹出框 */}
            <Modal
                open={showModal}
                title="添加用户"
                okText="确定"
                cancelText="取消"
                onCancel={() => {
                    setshowModal(false)
                    myFrom.current.resetFields();
                }}
                onOk={() => {
                    ModalConfirm()
                }}
            >
                <ModelForm
                    regionList={regionList}
                    roleList={roleList}
                    isEdit={false}
                    ref={myFrom} />
            </Modal>
            {/* 编辑用户弹出框 */}
            <Modal
                open={showUpdate}
                title="编辑用户"
                okText="确定"
                cancelText="取消"
                onCancel={() => {
                    setshowUpdate(false)
                    setisUpdateDisabled(!isUpdateDisabled)
                }}
                onOk={() => {
                    UpdateConfirm()
                }}
            >
                <ModelForm regionList={regionList}
                    isUpdateDisabled={isUpdateDisabled}
                    roleList={roleList}
                    ref={myUpdataFrom}
                    isEdit={true}
                />
            </Modal>
        </div>
    )
}
